layui.use(['table','laytpl','layer', 'form', 'layedit'], function() {
	var table = layui.table;
	var laytpl = layui.laytpl;
	table.render({
		elem : '#user-table',
		url : '/admin/user/query.json',
		id : 'mytable',
		page : true,
		height : 'full-165',
		cols : [ [
			{
				checkbox : true,
				width : 80
			}
			, {
				field : 'userId',
				title : 'ID',
				width : 80
			}
			, {
				field : 'userName',
				title : '用户名',
				width : 180
			}
			, {
				field : 'realName',
				title : '真实姓名',
				width : 180
			}
			, {
				field : 'roleName',
				title : '角色',
				width : 180
			}
			, {
				field : 'rowAddTime',
				title : '新增时间',
				width : 160
			}
			, {
				field : 'rowUpdateTime',
				title : '更新时间',
				width : 160
			}
			, {
				field : 'rowUpdateTime',
				fixed : 'right',
				align : 'center',
				toolbar : '#optbar',
				width : 200
			}
		] ]
	});
	table.on('tool', function(obj){
	    var data = obj.data;
	    if(obj.event === 'del'){
	      layer.confirm('确定删除'+obj.data.realName+'吗？', function(index){
    	  $.ajax({
    		    type: 'POST',
    		    url: '/admin/user/deleteUser.json',
    		    data: {userId:obj.data.userId},
    		    success: function (data) {
    		        if(data.success){
    		        	obj.del();
    			        layer.close(index);
    		        }else{
    		        	layer.msg(data.message,{title:'错误',icon: 5,anim: 6,time: 0,btn:['确定']});
    		        }
    		    },
    		    error: function(data) {
    		    	layer.msg(data.responseText,{title:'错误',icon: 5,anim: 6,time: 0,btn:['确定']});
    		    },
    		    dataType: "json"
    		})
	      });
	    } else if(obj.event === 'edit'){
	      //layer.alert('编辑行：<br>'+ JSON.stringify(data))
	    	openAddMenuWindow('edit',data.userId);
	    }
	  });
	
	var $ = layui.$,
		active = {
			reload : function() {
				table.reload('mytable', {
					where : {
						userName : $('#userName').val(),
						roleId:$('#searchRoleId').val(),
					}
				});
			}
		};
	$('#searchButton').on('click', function() {
		var type = $(this).data('type');
		active[type] ? active[type].call(this) : '';
	});
	$('#addUser').click(function(){
		openAddMenuWindow('new');
	});
	$('#refresh').click(function(){
		table.reload('mytable');
	});
	$.ajax({
	    type: 'POST',
	    url: '/admin/role/getAllRole.json',
	    success: function (data) {
	        if(data.success){
	        	var htmltmp = '';
	        	$.each(data.result,function(i,item){
	        		htmltmp += '<option value="'+item.roleId+'">'+item.roleName+'</option>';
	        	});
	        	$('#searchRoleId').html(htmltmp);
	        	var form = layui.form;
	        	form.render();
	        }else{
	        	layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
	        }
	    },
	    error: function(data) {
	    	layer.msg(data.responseText,{icon: 5,anim: 6,time: 2000});
	    },
	    dataType: "json"
	})
	//------------------------------------------------
	function openAddMenuWindow(optname,userid) {
		var optstr = '新建用户';
		if(optname == 'edit'){
			optstr = '编辑用户';
		}
		var mylayer = layer.open({
			type : 1,
			title : optstr,
			skin : 'layui-layer-lan',
			anim : 5,
			shadeClose : false,
			//area : [ 'auto', '400px' ],
			offset: [($(window).height()/8), $(window).width()/4],
			content : '<div id="standardForm"></div>',
			btn : [ '提交', '取消' ],
			closeBtn : false,
			btn1 : function(index, layero) {
				$('#mybutton').click();
			},
			btn2 : function(index, layero) {
				layer.close(mylayer);
			}
		});
		var getTpl = formftl.innerHTML,
			view = document.getElementById('standardForm');
		laytpl(getTpl).render({}, function(html) {
			view.innerHTML = html;
		});
		var form = layui.form;
		form.render();
		if(optname == 'edit'){
			$('#optname').val('edit');
			$('input[name="passWord"]').removeAttr('lay-verify');
		}else{
			$('#optname').val('new');
		}
		form.verify({
			pass : function(value) {
				if (value != $('input[name="passWord"]').val()) {
					return '两次密码不一致';
				}
			}
		});
		//权限加载
		$.ajax({
		    type: 'POST',
		    url: '/admin/role/getAllRole.json',
		    success: function (data) {
		        if(data.success){
		        	var htmltmp = '';
		        	$.each(data.result,function(i,item){
		        		htmltmp += '<option value="'+item.roleId+'">'+item.roleName+'</option>';
		        	});
		        	$('#addRoleId').html(htmltmp);
		        	form.render();
		        }else{
		        	layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
		        }
		    },
		    error: function(data) {
		    	layer.msg(data.responseText,{icon: 5,anim: 6,time: 2000});
		    },
		    dataType: "json"
		})
		if(optname == 'edit'){
			$.ajax({
			    type: 'POST',
			    url: '/admin/user/query.json',
			    data: {userId:userid},
			    success: function (data) {
			        if(data.success){
			        	$('input[name="userId"]').val(data.data[0].userId);
			        	$('input[name="userName"]').val(data.data[0].userName);
			        	$('input[name="realName"]').val(data.data[0].realName);
			        	$('#addRoleId').val(data.data[0].roleId);
			        	form.render('select')
			        }else{
			        	layer.msg(data.message,{icon: 5,anim: 6,time: 2000});
			        }
			    },
			    error: function(data) {
			    	layer.msg(data.responseText,{icon: 5,anim: 6,time: 2000});
			    },
			    dataType: "json"
			})
		}
		
		
		/**
		 * 表单验证通过后在这里提交表单
		 */
		form.on('submit(mybutton)', function(data) {
			if(optname == 'edit'){
				$.ajax({
				    type: 'POST',
				    url: '/admin/user/updateuser.json',
				    data: data.field,
				    success: function (data) {
				    	
				        if(data.success){
				        	layer.msg(data.message);
				        	layer.close(mylayer);
				        	table.reload('mytable');
				        }else{
				        	layer.msg(data.message,{icon: 5,anim: 6,time: 2000});
				        }
				    },
				    error: function(data) {
				    	layer.msg(data.responseText,{icon: 5,anim: 6,time: 2000});
				    },
				    dataType: "json"
				})
			} else {
				$.ajax({
				    type: 'POST',
				    url: '/admin/user/adduser.json',
				    data: data.field,
				    success: function (data) {
				        if(data.success){
				        	layer.msg(data.message);
				        	layer.close(mylayer);
				        	table.reload('mytable');
				        }else{
				        	layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
				        }
				    },
				    error: function(data) {
				    	layer.msg(data.responseText,{icon: 5,anim: 6,time:0,btn:['确定']});
				    },
				    dataType: "json"
				})
			}
			return false;
		});
	}
	//------------------------------------------------
});